##连接miniqmt
##启动消息队列，订阅队列，获取买卖信号，触发买卖
from 连接交易 import QMTTrader
from 组件.rabbitmq import RabbitMQTickSubscriber
from 主程.基础配置 import settings
import json
import time
import threading
from datetime import datetime
from xtquant import xtconstant



class TradingSystem:
    """交易系统主类"""
    ##初始化
    def __init__(self):
        self.trader = QMTTrader()

        self.subscriber = None
        self.running = True
    ##启动交易系统
    def start(self):
        print("启动交易系统...")
        # 1. 启动QMT交易接口
        print("正在启动QMT交易接口...")
        if not self.trader.start():
            print("QMT启动失败，系统退出")
            return
        print("QMT交易接口启动成功")
        # 2. 启动消息队列订阅
        print("正在启动消息队列订阅...")
        self._start_message_queue()
        print("交易系统启动成功！")
        # 3. 保持系统运行
        self._keep_alive()
    ##启动消息队列订阅
    def _start_message_queue(self):
        try:
            # 创建订阅者
            self.subscriber = RabbitMQTickSubscriber(
                callback=self._process_trading_signal,
                exchange='tick_exchange',
                queue='tick_queue'
            )
            # 在后台线程中启动订阅
            self.subscriber_thread = threading.Thread(
                target=self._run_subscriber,
                daemon=True
            )
            self.subscriber_thread.start()
            print("消息队列订阅启动成功")
        except Exception as e:
            print(f"启动消息队列时发生错误: {e}")
    ##在后台运行订阅者
    def _run_subscriber(self):
        try:
            self.subscriber.start_consuming()
        except Exception as e:
            print(f"订阅者运行错误: {e}")
    ##处理交易信号
    def _process_trading_signal(self, ch, method, properties, body):
        try:
            # 解析交易信号
            signal_data = json.loads(body)
            # 验证信号格式
            if not self._validate_signal(signal_data):
                print(f"无效的交易信号格式: {signal_data}")
                return
            # 处理不同类型的交易信号
            signal_type = signal_data.get('type')
            stock_code = signal_data.get('code')
            order_remark = signal_data.get('order_remark')
            volume =100
            display_time = datetime.now().strftime('%H:%M:%S')
            
            if signal_type == 'buy':
                direction = xtconstant.STOCK_BUY
                print(f"{display_time}，买入{stock_code}")
                self.trader.callback.place_market_order(stock_code, volume, direction, order_remark)
            elif signal_type == 'sell':
                direction = xtconstant.STOCK_SELL
                print(f"{display_time}，卖出{stock_code}")
                self.trader.callback.place_market_order(stock_code, volume, direction, order_remark)
            else:
                print(f"未知的信号类型: {signal_type}")
                
        except Exception as e:
            print(f"处理交易信号时发生错误: {e}")


    ##数据格式校验
    def _validate_signal(self, signal_data):
        """验证交易信号格式"""
        required_fields = ['type', 'code','order_remark']
        
        for field in required_fields:
            if field not in signal_data:
                return False
                
        # 验证股票代码是否在配置中
        stock_codes = [stock['all_code'] for stock in settings.STOCK_CODE]
        if signal_data['code'] not in stock_codes:
            print(f"股票代码 {signal_data['code']} 不在配置列表中")
            return False
            
        return True
    ##保持活跃
    def _keep_alive(self):
        """保持系统运行"""
        print("系统运行中，按 Ctrl+C 退出...")
        try:
            while self.running:
                time.sleep(1)
                # self.trader.callback.look_orders()
        except KeyboardInterrupt:
            print("\n收到退出信号，正在关闭系统...")
            self.stop()
    ##停止
    def stop(self):
        """停止交易系统"""
        print("正在停止交易系统...")
        
        # 停止消息队列订阅
        if self.subscriber:
            try:
                self.subscriber.close()
                print("消息队列订阅已关闭")
            except:
                pass
        
        # 停止QMT交易接口
        if self.trader:
            try:
                self.trader.stop()
                print("QMT交易接口已关闭")
            except:
                pass
        
        print("交易系统已停止")


def main():
    trading_system = TradingSystem()
    try:
        trading_system.start()
    except KeyboardInterrupt:
        print("\n收到中断信号，正在关闭系统...")
    except Exception as e:
        print(f"系统运行期间发生错误: {e}")
    finally:
        trading_system.stop()


if __name__ == "__main__":
    main()